//
//  MBProgressHUD+SCHUDExtension.m
//  PhotoAlbum
//
//  Created by Chao Sheng on 2021/12/7.
//

#import "SCToolExtension.h"

@implementation UIImageView (SCNetImgExtension)

- (void)sc_setImageWithModel:(SCPhotoModel *)model progress:(void (^)(CGFloat progress, SCPhotoModel *model))progressBlock completed:(void (^)(UIImage * image, NSError * error, SCPhotoModel * model))completedBlock {
    
    NSString *urlPath = [model.imageNetworkingUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlPath];
    UIImage *placeholderImage = [UIImage sc_bundleImageNamed:@"LGQ-placeholderImg"];
    [self sd_setImageWithURL:url placeholderImage:placeholderImage options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        
        model.imgSize = placeholderImage.size;
        
        CGFloat progress = (CGFloat)receivedSize * 1.0 / expectedSize;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (progressBlock) {
                progressBlock(progress, model);
            }
        });
    } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if(!error)
        {
            if (image) {
                model.highQualityImage = image;
                model.tempImage = image;
                model.imgSize = image.size;
                model.downloadError = false;
            }
        } else {
            model.downloadError = true;
            model.tempImage = placeholderImage;
            model.imgSize = model.tempImage.size;
        }
        if (completedBlock) {
            completedBlock(image,error,model);
        }
    }];
}

@end

@implementation UIView (SCExtension)

- (UIViewController *)sc_currentViewController {
    
    UIResponder *next = [self nextResponder];
    
    while (next != nil) {
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        } else {
            next = [next nextResponder];
        }
    }
    
    return nil;
}

@end

@implementation MBProgressHUD (SCHUDExtension)

static CGFloat scDefaultDuration = 1.5f;
+ (void)showSCHudText:(NSString *)str {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:window];
    [MBProgressHUD setSCDefaultConfig:hud];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = str;
    [hud hideAnimated:YES afterDelay:scDefaultDuration];
}

+ (void)showSCLoadind:(NSString *)text {
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [MBProgressHUD hideHUDForView:window animated:YES];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    // 设置基本属性
    [self setSCDefaultConfig:hud];
    // 设置有否点击
    hud.userInteractionEnabled = NO;
    // 设置背景色
    hud.backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
    // 设置模式
    hud.mode = MBProgressHUDModeIndeterminate;
    // 设置文本
    if (text) {
        hud.label.text = text;
    }
}

+ (void)hideSCHud {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [MBProgressHUD hideHUDForView:window animated:YES];
}

+ (void)setSCDefaultConfig:(MBProgressHUD *)hud {
    
    // 设置控件的颜色
    hud.contentColor = [UIColor colorWithWhite:1 alpha:1];
    // 设置mask背景
    hud.backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
    // 设置text的颜色
    hud.label.font = [UIFont systemFontOfSize:15];
    hud.label.textColor = UIColor.whiteColor;
    hud.label.numberOfLines = 0;
    // 设置detailText的颜色
    hud.detailsLabel.font = [UIFont systemFontOfSize:13];
    hud.detailsLabel.textColor = UIColor.whiteColor;
    // 设置hud背景框的颜色
    hud.bezelView.color = [UIColor colorWithWhite:0 alpha:0.8];
    // 设置hud隐藏自动移除功能
    hud.removeFromSuperViewOnHide = YES;
    // 设置hud显示和隐藏动画
    hud.animationType = MBProgressHUDAnimationZoom;
}

@end

@implementation NSDate (SCDateExtension)

/**
 *  是否为今天
 */
- (BOOL)isToday {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear;
    
    // 1.获得当前时间的年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
    
    // 2.获得self的年月日
    NSDateComponents *selfCmps = [calendar components:unit fromDate:self];
    return
    (selfCmps.year == nowCmps.year) &&
    (selfCmps.month == nowCmps.month) &&
    (selfCmps.day == nowCmps.day);
}
/**
 *  是否为昨天
 */
- (BOOL)isYesterday {
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyyMMdd";
    
    // 生成只有年月日的字符串对象
    NSString *selfString = [fmt stringFromDate:self];
    NSString *nowString = [fmt stringFromDate:[NSDate date]];
    
    // 生成只有年月日的日期对象
    NSDate *selfDate = [fmt dateFromString:selfString];
    NSDate *nowDate = [fmt dateFromString:nowString];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *cmps = [calendar components:unit fromDate:selfDate toDate:nowDate options:0];
    return cmps.year == 0
    && cmps.month == 0
    && cmps.day == 1;
}
/**
 *  是否为今年
 */
- (BOOL)isThisYear {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitYear;
    
    // 1.获得当前时间的年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
    
    // 2.获得self的年月日
    NSDateComponents *selfCmps = [calendar components:unit fromDate:self];
    
    return nowCmps.year == selfCmps.year;
}

/**
 是否为同一周内
 */
- (BOOL)isSameWeek {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitWeekday | NSCalendarUnitMonth | NSCalendarUnitYear ;
    
    //1.获得当前时间的 年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
    
    //2.获得self
    NSDateComponents *selfCmps = [calendar components:unit fromDate:self];
    
    return (selfCmps.year == nowCmps.year) && (selfCmps.month == nowCmps.month) && (selfCmps.day == nowCmps.day);
}
- (NSString *)getNowWeekday {
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"MM月dd日"];
    [dateday setDateFormat:@"EEEE"];
    return [dateday stringFromDate:self];
}

- (NSString *)dateStringWithFormat:(NSString *)format {
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    formater.dateFormat = format;
    return[formater stringFromDate:self];
}



@end

@implementation UIImage (SCOrientationExtension)

+ (UIImage *)changeOrientation:(SCImageOrientation)orientation image:(UIImage *)image {
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
                                             CGImageGetBitsPerComponent(image.CGImage),0,
                                             CGImageGetColorSpace(image.CGImage),
                                             CGImageGetBitmapInfo(image.CGImage));
    
    if (orientation==SCImageOrientationLeft) { //横向
        CGFloat h = image.size.width*image.size.width/image.size.height;
        CGFloat y = (image.size.height - h)/2;
        CGContextDrawImage(ctx,CGRectMake(0,y,image.size.width,h), image.CGImage);
    } else if(orientation==SCImageOrientationUp){ //垂直
        CGAffineTransform transform = CGAffineTransformIdentity;
        transform = CGAffineTransformTranslate(transform,0,image.size.height);
        transform = CGAffineTransformRotate(transform, -M_PI_2);
        CGContextConcatCTM(ctx, transform);
        CGContextDrawImage(ctx,CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

+ (UIImage *)sc_bundleImageNamed:(NSString *)name {
    NSBundle *bundle = [NSBundle bundleForClass:NSClassFromString(@"SCPhotoView")];
    NSURL *bundleURL = [bundle URLForResource:@"SCKitLib" withExtension:@"bundle"];
    NSString *path = [[NSBundle bundleWithURL:bundleURL] pathForResource:name ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    
    return image;
    
}

@end

